/**
 * Created by Administrator on 2014/4/30.
 */

var gui = require('nw.gui');
var socket = global.pubdata.socket;
var user = global.pubdata.user;
var ulist = $("#leftad ul");
var roomwin = null;
var ckid='chatinput';
var msgId='chatcontent';


function minisize(event) {
    roomwin.minimize();
}
onload = function () {
    socket.emit('userJoin',user.name);
    roomwin = gui.Window.get()
}
socket.on('message', function (data) {
    appendMessage(msgId,data);
    if (hiddened) {
        checkhitwin({message:data.content,socket:socket});
    }
});

socket.on('logoutEvent',function(data){
    roomwin.close(true);
});

socket.on('userJoin', function (data) {

    ulist.empty();
    $.each(data.users, function (i, item) {
        ulist.append(item.content);

    });

    saysAutoScroll('leftad');

});
socket.on("notified", function (data) {
    appendMessagePanel(ckid,data);
});
function appendMessagePanel(pid,datas) {

    var chatsays = $("#"+pid);

    var panel = $("<div></div>").addClass("mPanel");
    var mul = $("<ul></ul>");
    var mids = [];
    $.each(datas, function (i, msg) {
        var mline = $("<li></li>").html(msg.body);
        mul.append(mline);
        mids.push(msg.id);
    });


    var ignorebtn = $("<button class='btn btn-danger btn-mini'><i class='icon-ban-circle'></i>不再提醒</button>");
    ignorebtn.bind('click', function (event) {
        ignoreit(mids.join(","), event);

    });

    var oabtn = $("<button class='btn btn-primary btn-mini'><i class='icon-circle'></i>登录OA</button>");
    oabtn.bind('click', function (event) {
        openOa();
        $(event.target).prop('disabled', true);
    });
    var cline = $("<li></li>").append(ignorebtn).append(oabtn);
    mul.append(cline);
    panel.append(mul);
    var line = $("<li></li>").html(panel);
    chatsays.append(line);
    saysAutoScroll('showcontent');
}
function openOa(event) {
    gui.Shell.openExternal('https://pdt.qinghua.com:8443/myapps/login');
}

function ignoreit(s, event) {
    var params = s;
    socket.emit('ignoreNotify', params);
    $(event.target).prop('disabled', true);
}

function appendMessageList(pid,datas){
    $.each(datas, function (idx, item) {
        appendMessage(pid,item);
    });
}


function sendMessage(ckid) {
    var msg = getCkData(ckid);
    if (msg == '' || msg == null) return;
    socket.send(msg);
    safecleanckeditor(ckid);
}

$(function(){
   render('chatinput');
    $('#sendpubbtn').bind('click',function(event){
        sendMessage('chatinput');
    })
})

